package com.starblink.home.subscription.cell

import android.view.Gravity
import androidx.core.view.marginLeft
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.drawable
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.sensorsdata.extension.trackBizSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.basic.ext.load
import com.starblink.basic.ext.nowTime
import com.starblink.home.R
import com.starblink.home.databinding.CellSubsItemMainBinding
import com.starblink.home.subscription.data.TYPE_SUBS_MSG_BRAND
import com.starblink.home.subscription.data.TYPE_SUBS_MSG_GOODS
import com.starblink.home.subscription.data.TYPE_SUBS_MSG_STORE
import com.starblink.rocketreserver.fragment.SubscriptionMessageRespF
import org.joda.time.DateTime
import java.util.Locale

/**
 *  Create by yuanl at 2023/9/28
 **/
class SubscriptionCell(
    binding: CellSubsItemMainBinding,
    private val brandMsgClick: ((SubscriptionMessageRespF?) -> Unit)? = null,
    private val prdMsgClick: ((SubscriptionMessageRespF?) -> Unit)? = null,
    private val merchantMsgClick: ((SubscriptionMessageRespF?) -> Unit)? = null
) :
    BaseBindingVH<SubscriptionMessageRespF, CellSubsItemMainBinding>(binding) {

    companion object {
        const val VALID_TIME_MILLI = 5 * 24 * 60 * 60 * 1000
    }

    private val today0Clock = DateTime().let {
        DateTime(it.year, it.monthOfYear, it.dayOfMonth, 0, 0).millis
    }

    init {
        binding.img.enableCorner(6.dp)
    }

    override fun onBind(model: SubscriptionMessageRespF, position: Int) {

        var millis: Long? = null
        binding.tvTime.text = (model.messageTime as? String)?.let {
            kotlin.runCatching {
                val date = DateTime(it).toLocalDate()
                //millis = date.toDate()?.time
                millis = DateTime(date.year, date.monthOfYear, date.dayOfMonth, 0 ,0).millis
                date.toString("dd/MMM/yyyy", Locale.ENGLISH)
            }.getOrNull()
        }
        binding.groupInvalid.visibleOrGone(millis == null || (today0Clock - millis!! >= VALID_TIME_MILLI))
        binding.vBgInvalid.setOnClickListener {

        }
        when (model.messageType) {
            TYPE_SUBS_MSG_BRAND -> {
                model.bindBrand()
            }

            TYPE_SUBS_MSG_STORE -> {
                model.bindStore()
            }

            TYPE_SUBS_MSG_GOODS -> {
                model.bindGoods()
            }

            else -> {
                clearViews()
            }
        }
        itemView.trackData(
            findParentPageSpmId(),
            SpmElementDef.ELE_30165,
            params = mutableMapOf<String, String>().apply {
                findParentPageSpmParams()?.takeIf { it.isNotEmpty() }?.let {
                    putAll(it)
                }
                put("messageId", model.messageId.orEmpty())
            },
            businessSuffixID = model.trackBizSuffixId(),
        )
        binding.tvDiscount.setOnClickListener {
            itemView.performClick()
        }
    }

    private fun SubscriptionMessageRespF.bindBrand() {
        binding.tvTitle.text = "Brand Outlets"
        binding.ic.setImageResource(R.drawable.ic_svg_subs_tab_brands)
        binding.ic.setBackgroundResource(R.drawable.bg_subs_ic_brand)
        binding.vBgMain.setBackgroundResource(R.drawable.bg_home_subs_item_brand)
        binding.tvDiscountCorner.gone()
        binding.layoutPrice.gone()
        binding.layoutImg.visible()
        binding.layoutPrice.gone()
        binding.tvDiscount.gone()
        binding.img.setImageDrawable(null)

        binding.imgLogo.boardWidth = 1.dp

        discountBrandMessage?.disCountBrandMessageF?.let {
            binding.tvContent.text = it.title?.trim()

            binding.layoutLogo.visible()
            binding.imgLogo.load(it.logo, it.brandName, hasDefaultHolder = false)
            binding.imgLogo.corner = 100000f

            binding.img.load(it.discountOfferPic, error = drawable(R.drawable.subs_img_err))

            binding.tvDiscount.visibleOrGone(it.promotionMsg?.isNotEmpty() == true) {
                //text = it.promotionMsg
                buildSpannableString {
                    addText(it.promotionMsg!!)
                    addImage(com.starblink.home.R.drawable.ic_subs_msg_arron, verticalAlignment = 4, maginLeft = 2.dp, width = 16.dp, height = 16.dp)
                }
//                this.buildSpannableString {
//                    addText("Up to ")
//                    addText(discount) {
//                        typeface = FontUtil.getTypeface(FontUtil.DM_SANS_BOLD)
//                    }
//                    addText("% off")
//                }
            }
        }

        itemView.setOnClickListener {
            //brandMsgClick?.invoke(discountBrandMessage?.disCountBrandMessageF)
            brandMsgClick?.invoke(this)
        }
    }

    private fun SubscriptionMessageRespF.bindStore() {
        binding.tvTitle.text = "Store Deals"
        binding.ic.setImageResource(R.drawable.ic_svg_subs_tab_stores)
        binding.ic.setBackgroundResource(R.drawable.bg_subs_ic_store)
        binding.vBgMain.setBackgroundResource(R.drawable.bg_home_subs_item_store)

        binding.tvDiscountCorner.gone()
        binding.layoutPrice.gone()
        binding.layoutImg.visible()
        binding.tvDiscount.gone()
        binding.img.setImageDrawable(null)

        binding.imgLogo.boardWidth = 0.dp

        discountStoreMessage?.discountStoreMessageF?.let {
            binding.tvContent.text = it.title?.trim()

            binding.layoutLogo.visible()
            binding.imgLogo.corner = 8.dp.toFloat()
            binding.imgLogo.load(it.logo, it.merchantWebName, hasDefaultHolder = false)

            binding.img.load(it.pic, error = drawable(R.drawable.subs_img_err))

            binding.tvDiscount.visibleOrGone(it.promotionMsg?.isNotEmpty() == true) {
                //text = it.promotionMsg
                buildSpannableString {
                    addText(it.promotionMsg!!)
                    addImage(com.starblink.home.R.drawable.ic_subs_msg_arron, verticalAlignment = 4, maginLeft = 2.dp, width = 16.dp, height = 16.dp)
                }
//                this.buildSpannableString {
//                    addText("Up to ")
//                    addText(discount) {
//                        typeface = FontUtil.getTypeface(FontUtil.DM_SANS_BOLD)
//                    }
//                    addText("% off")
//                }
            }
        }

        itemView.setOnClickListener {
            //merchantMsgClick?.invoke(discountStoreMessage?.discountStoreMessageF)
            merchantMsgClick?.invoke(this)
        }
    }

    private fun SubscriptionMessageRespF.bindGoods() {
        binding.tvTitle.text = "Price Drop"
        binding.ic.setImageResource(R.drawable.ic_svg_subs_tab_items)
        binding.ic.setBackgroundResource(R.drawable.bg_subs_ic_prd)
        binding.vBgMain.setBackgroundResource(R.drawable.bg_home_subs_item_goods)
        binding.layoutLogo.gone()
        binding.tvDiscount.gone()
        binding.layoutPrice.gone()
        binding.img.setImageDrawable(null)

        discountProductMessage?.discountProductMessageF?.let {
            binding.tvContent.text = it.title?.trim()
            binding.img.load(it.mainUrl, error = drawable(R.drawable.subs_img_err))
            binding.layoutPrice.visibleOrGone(it.price?.isNotEmpty() == true) {
                binding.vPrice.show(it.price!!, it.currency, it.currencySymbol)
            }
            val hasDiscount = it.discount?.isNotEmpty() == true && it.discount != "0"
            binding.vPriceO.visibleOrGone(it.oldPrice?.isNotEmpty() == true && hasDiscount) {
                show(it.oldPrice!!, it.currency, it.currencySymbol)
            }
            binding.tvDiscountCorner.visibleOrGone(hasDiscount) {
                text = "-${it.discount}%"
            }
        }
        itemView.setOnClickListener {
            //prdMsgClick?.invoke(discountProductMessage?.discountProductMessageF)
            prdMsgClick?.invoke(this)
        }
    }

    private fun clearViews() {
        binding.tvTitle.text = null
        binding.ic.setImageDrawable(null)
        binding.ic.background = null

        binding.tvContent.text = null

        binding.tvDiscount.text = null

        binding.img.setImageDrawable(null)
        binding.tvDiscountCorner.gone()
        binding.layoutPrice.gone()

        binding.groupInvalid.gone()

        binding.layoutLogo.gone()

        itemView.setOnClickListener(null)
    }

}